<template>
  <div id="headerBar" ref="headerBar" class="auto_fixed" :class="auto_fixed" :style="{width:width, 'min-height':height,'line-height':lineHeight}">
    <div>
      <slot></slot>
    </div>
  </div>
</template>
<script>
import {mapState} from 'vuex'

export default {
  name: 'HeaderToobar',
  data() {
    return {
      auto_fixed: {
        fixed: false
      },
      extra: {
        type: [String, Object],
        default: ''
      },
      width: '100%',
      height: '36px',
      lineHeight: '36px',
      // 是否吸顶
      ifFixed: false,
      // 目标元素与整个文档顶部间的距离
      targetTop: 0,
      headerBarTop: 0,
      scrollTop: 0,
      offsetHeight:0
    }
  },

  computed: {
    ...mapState('setting', ['isMobile', 'layout',
      'fixedTabs', 'fixedHeader', 'multiPage', 'collapsed']),

  },
  watch: {
    layout(val) {
      this.getWidth()
    },
    collapsed(val) {
      this.getWidth()
    },
    fixedTabs(val) {
      this.getHeight()
    },
    fixedHeader(val) {
      this.getHeight()
    }
  },
  methods: {
    getWidth() {
      let width = window.innerWidth;
      let subWidth = 34
      if (this.layout !== 'head') {
        if (this.collapsed) {
          subWidth = subWidth + 80
        } else {
          subWidth = subWidth + 256
        }

      }
      let theWidth = width - subWidth
      this.width = theWidth + 'px'
      return theWidth
    },
    getHeight() {

    },
    onResize() {
      this.getWidth()
      this.onScroll()
    },
    onScroll() {
      // 获取当前滚动条向下滚动的距离
      let scrollTop = document.getElementById('admin-layout-main').scrollTop|| window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
      this.ifFixed = scrollTop > this.targetTop;
      this.auto_fixed = {
        auto_fixed: true,
        fixed: this.ifFixed,
        top: '0px',
        right: 0,/*这句很重要*/
        width: this.width
      }
    },
  },
  mounted() {
    this.getWidth()
    //当屏幕变化的时候要重新计算不然会出问题，因为滚动高度会变
    this.$nextTick(function () {  
        // 获取吸顶元素的dom
        let header = this.$refs.headerBar;
        // 元素自身的高度
        this.offsetHeight = header.offsetHeight;
        
        document.getElementById('admin-layout-main').addEventListener('resize', this.onResize,true);
        document.getElementById('admin-layout-main').addEventListener('scroll', this.onScroll,true);
    })
  },
  destroyed() {
    // 移除监听
    document.getElementById('admin-layout-main').removeEventListener("resize", this.onResize, false);
    document.getElementById('admin-layout-main').removeEventListener("scroll", this.onScroll, false);
  }
}
</script>
<style lang="less" scoped>
.auto_fixed {
  position: relative;
  background: #fff;
  z-index: 999;
  //top: 100px;
  text-align: right;
  margin-bottom: 10px;
  padding: 0 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.09);
  border-bottom: 1px solid #e8e8e8;
}

.fixed {
  position: fixed;
  top: 0;
  //width: 100%;
}
</style>